import React, { useState } from 'react';
import {
  Box,
  TextField,
  Button,
  Paper,
  Typography,
  Container,
  Alert,
} from '@mui/material';
import axios from 'axios';

const API_BASE_URL = 'http://localhost:5000';

const StudentView = () => {
  const [question, setQuestion] = useState('');
  const [studentName, setStudentName] = useState('');
  const [studentId, setStudentId] = useState('');
  const [submitted, setSubmitted] = useState(false);
  const [error, setError] = useState(null);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setError(null);
    try {
      const response = await axios.post(`${API_BASE_URL}/api/questions`, {
        content: question,
        studentName,
        studentId,
      }, {
        timeout: 5000, // 5秒超时
      });
      
      if (response.status === 201) {
        setSubmitted(true);
        setQuestion('');
        setStudentName('');
        setStudentId('');
      }
    } catch (error) {
      console.error('提交问题出错:', error);
      if (error.code === 'ECONNREFUSED') {
        setError('无法连接到服务器，请确保服务器正在运行');
      } else if (error.response) {
        setError(`服务器错误: ${error.response.data.error}`);
      } else {
        setError('提交问题失败，请稍后重试');
      }
    }
  };

  return (
    <Container maxWidth="sm">
      <Paper elevation={3} sx={{ p: 4, mt: 4 }}>
        <Typography variant="h4" component="h1" gutterBottom>
          提交问题
        </Typography>
        {error && (
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
        )}
        {submitted ? (
          <Alert severity="success" sx={{ mb: 2 }}>
            问题提交成功！
          </Alert>
        ) : (
          <Box component="form" onSubmit={handleSubmit}>
            <TextField
              fullWidth
              label="姓名"
              value={studentName}
              onChange={(e) => setStudentName(e.target.value)}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="学号"
              value={studentId}
              onChange={(e) => setStudentId(e.target.value)}
              margin="normal"
              required
            />
            <TextField
              fullWidth
              label="你的问题"
              value={question}
              onChange={(e) => setQuestion(e.target.value)}
              margin="normal"
              multiline
              rows={4}
              required
            />
            <Button
              type="submit"
              variant="contained"
              color="primary"
              sx={{ mt: 2 }}
            >
              提交问题
            </Button>
          </Box>
        )}
      </Paper>
    </Container>
  );
};

export default StudentView; 